N = 55
K = 5
count = 0
factor = 1

while factor <= N:
    high = N // (factor * 10)
    current = (N // factor) % 10
    low = N % factor

    if current > K:
        count += (high + 1) * factor
    elif current == K:
        count += high * factor + low + 1
    else:
        count += high * factor

    if K == 0:
        count -= factor

    factor *= 10

print(count)  # 输出2


def count_k_occurrences(n, k):
    count = 0
    factor = 1
    while factor <= n:
        divisor = factor * 10
        higher = n // divisor
        current = (n // factor) % 10
        lower = n % factor

        if k == 0:
            if factor == 1:
                # 处理个位
                if current > k:
                    count += (higher + 1) * factor
                elif current == k:
                    count += higher * factor + lower + 1
                else:
                    count += higher * factor
            else:
                # 处理其他位，高位必须大于0
                if higher > 0:
                    if current > k:
                        count += higher * factor
                    elif current == k:
                        count += (higher - 1) * factor + lower + 1
                    else:
                        count += higher * factor
        else:
            # k非0的情况
            if current > k:
                count += (higher + 1) * factor
            elif current == k:
                count += higher * factor + lower + 1
            else:
                count += higher * factor

        factor *= 10
    return count


print(count_k_occurrences(55, 5))  # print:56
